package com.local.admin.service.impl;

import com.local.admin.constants.AdminConstants;
import com.local.admin.mapper.AdminUserMapper;
import com.local.admin.pojo.AdminUser;
import com.local.admin.service.AdminUserService;
import com.local.common.util.MD5Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Objects;

/**
 * 后台用户操作业务类
 */
@Service
public class AdminUserServiceImpl implements AdminUserService {

    @Autowired
    private AdminUserMapper adminUserMapper;

    /**
     * 后台用户登录，获取用户记录
     * @param userName
     * @param password
     * @return
     */
    @Override
    public AdminUser login(String userName, String password) {
        String passwordMd5 = MD5Util.MD5Encode(password, AdminConstants.UTF_ENCODING);
        return adminUserMapper.login(userName, passwordMd5);
    }

    @Override
    public AdminUser selectById(Integer adminUserId) {
        return adminUserMapper.selectById(adminUserId);
    }


    /**
     * 修改用户名和昵称
     * @param adminUserId
     * @param loginUserName
     * @param nickName
     * @return
     */
    @Override
    public Integer updateName(Integer adminUserId, String loginUserName, String nickName) {
        AdminUser adminUser = adminUserMapper.selectByLoginUserName(loginUserName);
        if (!Objects.isNull(adminUser) && adminUser.getAdminUserId() != adminUserId) {
            return -1;
        } else {
            return adminUserMapper.updateName(adminUserId, loginUserName, nickName);
        }
    }


    /**
     * 修改密码
     * @param adminUserId
     * @param originalPassword
     * @param newPassword
     * @return
     */
    @Override
    public Integer updatePassword(Integer adminUserId, String originalPassword, String newPassword) {
        AdminUser adminUser = adminUserMapper.selectById(adminUserId);
        if (Objects.isNull(adminUser)) {
            return -1;
        }

        String originalPasswordMD5 = MD5Util.MD5Encode(originalPassword, AdminConstants.UTF_ENCODING);
        //验证原始密码是否一致
        if (originalPasswordMD5.equals(adminUser.getLoginPassword())) {
            //更新密码
            return adminUserMapper.updatePassword(adminUserId, MD5Util.MD5Encode(newPassword, AdminConstants.UTF_ENCODING));
        } else {
            //原密码错误
            return -2;
        }
    }
}
